<script lang="ts">
import { defineComponent, ref, watch, computed, reactive } from "vue";
import { UserModule } from "@/store/modules/user";
import {
    getUserInfo,
    getTradeParameter,
    getTokenPrice,
    getTradeRecordList,
} from "@/api/nodeapi";
import { showToast, showDialog, showConfirmDialog } from "vant";
import { toStringMatch, formatAddress } from "@/utils/format";
import { USDT_TOKEN } from "@/contract";
import { useI18n } from "vue-i18n";
import { BalanceOf } from "@/contract/Erc20";
import Clipboard from "clipboard";

export default defineComponent({
    setup() {
        const { t } = useI18n();
        const active = ref(0);
        const pageLoading = ref(true);
        const loading2 = ref(false);
        const userInfo = ref({});
        const tradeParameter = ref({});
        const nodeTRX = ref(0);
        const amount = ref();
        const TRX = ref(0);
        const USDT = ref(0);
        const _usdtSendAddr = ref(0);
        const _trxSendAddr = ref(0);
        const setat = reactive({
            pageNum: 1,
            pageSize: 10,
            total: 0,
        });
        const refreshing = ref(false);
        const loading = ref(true);
        const finished = ref(false);
        const list: any = ref([]);
        const onRefresh = () => {
            // setat.pageNum = 0;
            // finished.value = false;
            // loading.value = true;
            // refreshing.value = true;
            onLoad();
        };
        const onLoad = async () => {
            const res = await getTradeRecordList({
                address: UserModule.userAddr,
                pageNum: setat.pageNum - 1,
                pageSize: setat.pageSize,
            });

            list.value = res.data.data.TradeRecordList || [];
            setat.total = res.data.data.Total;
            loading.value = false;
        };

        const onSubmit = async ({}) => {
            loading2.value = true;
            try {
                if (active.value == 0) {
                    const functionSelector = "transfer(address,uint256)";
                    const parameter = [
                        {
                            type: "address",
                            value: tradeParameter.value.SendAddr,
                        },
                        { type: "uint256", value: toSun.value(amount.value) },
                    ];
                    const tx =
                        await tronWeb.transactionBuilder.triggerSmartContract(
                            USDT_TOKEN,
                            functionSelector,
                            {},
                            parameter
                        );
                    const signedTx = await tronWeb.trx.sign(tx.transaction);
                    var result = await tronWeb.trx.sendRawTransaction(signedTx);
                } else {
                    var transaction = await tronWeb.transactionBuilder.sendTrx(
                        tradeParameter.value.SendAddr,
                        toSun.value(amount.value),
                        UserModule.userAddr
                    );
                    const signedTx = await tronWeb.trx.sign(transaction);
                    var result = await tronWeb.trx.sendRawTransaction(signedTx);
                }
                if (result.result) {
                    showDialog({ title: `${t("layout.success")}` });
                    amount.value = "";
                } else {
                    showToast({
                        message: `${t("layout.fail")}`,
                        icon: "clear",
                        className: "_showToast2",
                        position: "top",
                    });
                }
                console.log(result);
            } catch (error) {}
            loadData();
            loading2.value = false;
        };
        const loadData = async () => {
            try {
                getUserInfo().then((res) => {
                    userInfo.value = res.data.data.UserInfo || {};
                });

                getTradeParameter().then((res) => {
                    tradeParameter.value = res.data.data.TradeParameter || {};
                    BalanceOf(tradeParameter.value.SendAddr).then((res) => {
                        _usdtSendAddr.value = res;
                    });
                    tronWeb.trx
                        .getBalance(tradeParameter.value.SendAddr)
                        .then((res) => {
                            _trxSendAddr.value = res;
                        });
                });
                getTokenPrice().then((res) => {
                    nodeTRX.value = res.data.data.PriceList[0].Price;
                });
                await tronWeb.trx
                    .getBalance(UserModule.userAddr)
                    .then((res) => {
                        TRX.value = res;
                    });
                const _usdt = await BalanceOf(UserModule.userAddr);
                USDT.value = _usdt;

                pageLoading.value = false;
            } catch (error) {}
        };
        const validatorMessage1 = (val) => {
            if (Number(val) < tradeParameter.value.UsdtMin) {
                return false;
            } else if (
                getTRX.value >
                toStringMatch(fromSun.value(_trxSendAddr.value), 4)
            ) {
                return false;
            } else {
                return true;
            }
        };
        const validatorMessage2 = (val) => {
            if (Number(val) < tradeParameter.value.TrxMin) {
                return false;
            } else if (
                getUSDT.value >
                toStringMatch(fromSun.value(_usdtSendAddr.value), 4)
            ) {
                return false;
            } else {
                return true;
            }
        };
        const getTRX = computed(() => {
            return toStringMatch(amount.value * (1 / nodeTRX.value), 4);
        });
        const getUSDT = computed(() => {
            return toStringMatch(amount.value * nodeTRX.value, 4);
        });
        const toSun = computed(() => {
            return (data) => {
                return tronWeb.toSun(data);
            };
        });
        const fromSun = computed(() => {
            return (data) => {
                return tronWeb.fromSun(data);
            };
        });
        const copy = async (id: string) => {
            const clipboard = new Clipboard(id);
            clipboard.on("success", () => {
                showToast({
                    message: t("layout.copySuccessfully"),
                    icon: "checked",
                    className: "_showToast",
                });
                clipboard.destroy();
            });
            clipboard.on("error", () => {
                showToast(t("layout.fail"));
                clipboard.destroy();
            });
        };
        watch(
            () => UserModule.userAddr,
            (newUserAddr: string) => {
                if (newUserAddr) {
                    loadData();
                    onRefresh();
                }
            },
            { immediate: true }
        );
        return {
            active,
            userInfo,
            tradeParameter,
            nodeTRX,
            amount,
            loading2,
            pageLoading,
            TRX,
            USDT,
            getTRX,
            getUSDT,
            _usdtSendAddr,
            _trxSendAddr,
            fromSun,
            onSubmit,
            toStringMatch,
            validatorMessage1,
            validatorMessage2,
            copy,
            formatAddress,
            list,
            setat,
            refreshing,
            finished,
            onRefresh,
            onLoad,
            loading,
            UserModule,
        };
    },
});
</script>

<template>
    <div class="main2">
        <div class="page">
            <div class="rowAward">
                <div class="cell">
                    <div class="label">
                        <img
                            src="@/assets/image/USDT.svg"
                            alt=""
                            srcset=""
                        />USDT
                    </div>
                    <div class="value">{{ fromSun(USDT) || 0 }}</div>
                </div>
                <div class="cell">
                    <div class="label">
                        <img src="@/assets/logo3.png" alt="" srcset="" />TRX
                    </div>
                    <div class="value">{{ fromSun(TRX) || 0 }}</div>
                </div>
                <div class="cell">
                    <div class="label">
                        <img src="@/assets/logo3.png" alt="" srcset="" />{{
                            $t("layout.Currentexchangerate")
                        }}
                    </div>
                    <div class="value">{{ nodeTRX || 0 }}USDT</div>
                </div>
            </div>
            <van-form @submit="onSubmit">
                <van-tabs v-model:active="active">
                    <van-tab :title="$t('layout.ConvertUSDTtoTRX')">
                        <div class="inputBlock">
                            <div class="name">
                                {{ $t("layout.EnterUSDTamount") }}
                                <span>
                                    {{
                                        `* ${$t("layout.text102")}：${
                                            tradeParameter.UsdtMin || 0
                                        }`
                                    }}</span
                                >
                            </div>
                            <van-field
                                v-model="amount"
                                class="address"
                                :placeholder="$t('layout.EnterUSDTamount')"
                                :rules="[
                                    { required: true },
                                    { validator: validatorMessage1 },
                                ]"
                            />
                            <div class="balance">
                                {{ $t("layout.Availablebalance") }}：{{
                                    toStringMatch(fromSun(USDT), 4) || 0
                                }}
                                USDT
                            </div>
                            <div class="name">
                                {{ $t("layout.ReceiveTRXamount") }}
                                <span
                                    >*
                                    {{ $t("layout.MaximumTradingVolume") }}：{{
                                        toStringMatch(fromSun(_trxSendAddr), 4)
                                    }}</span
                                >
                            </div>
                            <div class="getAmount">
                                <span v-if="!amount">0.00</span>
                                <template v-else>{{
                                    toStringMatch(
                                        getTRX -
                                            (getTRX * tradeParameter.Fee) /
                                                1000,
                                        4
                                    )
                                }}</template>
                            </div>
                        </div>
                        <van-button
                            round
                            block
                            type="primary"
                            :disabled="
                                pageLoading || !validatorMessage1(amount)
                            "
                            native-type="submit"
                            :loading="loading2"
                        >
                            {{ $t("layout.Confirmthetransaction") }}
                        </van-button>
                    </van-tab>
                    <!-- <van-tab :title="$t('layout.ConvertTRXtoUSDT')">
                        <div class="inputBlock">
                            <div class="name">
                                {{ $t("layout.EnterTRXamount") }}
                                <span>
                                    {{
                                        `* ${$t("layout.text102")}：${
                                            tradeParameter.TrxMin || 0
                                        }`
                                    }}</span
                                >
                            </div>
                            <van-field
                                v-model="amount"
                                class="address"
                                :placeholder="$t('layout.EnterTRXamount')"
                                :rules="[
                                    { required: true },
                                    { validator: validatorMessage2 },
                                ]"
                            />
                            <div class="balance">
                                {{ $t("layout.Availablebalance") }}：{{
                                    toStringMatch(fromSun(TRX), 4) || 0
                                }}
                                TRX
                            </div>
                            <div class="name">
                                {{ $t("layout.ReceiveUSDTamount") }}
                                <span
                                    >*
                                    {{ $t("layout.MaximumTradingVolume") }}：{{
                                        toStringMatch(fromSun(_usdtSendAddr), 4)
                                    }}</span
                                >
                            </div>
                            <div class="getAmount">
                                <span v-if="!amount">0.00</span>
                                <template v-else>{{
                                    toStringMatch(
                                        getUSDT -
                                            (getUSDT * tradeParameter.Fee) /
                                                1000,
                                        4
                                    )
                                }}</template>
                            </div>
                        </div>
                        <van-button
                            round
                            block
                            type="primary"
                            :disabled="
                                pageLoading || !validatorMessage2(amount)
                            "
                            native-type="submit"
                            :loading="loading2"
                        >
                            {{ $t("layout.Confirmthetransaction") }}
                        </van-button>
                    </van-tab> -->
                </van-tabs>
            </van-form>

            <div class="listTitle">{{ $t("layout.TransactionRecords") }}</div>
            <div class="list">
                <div class="scroll">
                    <div class="head">
                        <span>{{ $t("layout.Transactiontime") }}</span>
                        <span>{{ $t("layout.Type") }}</span>
                        <span>{{ $t("layout.Paidamount") }}</span>
                        <span>{{ $t("layout.Receivedamount") }}</span>
                        <span>{{ $t("layout.Transactionhash") }}</span>
                        <span>{{ $t("layout.state") }}</span>
                    </div>
                    <ul>
                        <li v-for="(item, index) in list" :key="index">
                            <div>{{ item.CreatedAt }}</div>
                            <div>
                                <template v-if="item.TokenType == 0"
                                    >USDT-->TRX</template
                                >
                                <template v-else>TRX-->USDT</template>
                            </div>
                            <div>
                                {{ item.TokenAmount }}
                                <template v-if="item.TokenType == 0"
                                    >USDT</template
                                >
                                <template v-else>TRX</template>
                            </div>
                            <div>
                                {{ item.TradeAmount }}
                                <template v-if="item.TokenType == 0"
                                    >TRX</template
                                >
                                <template v-else>USDT</template>
                            </div>

                            <div
                                class="address"
                                :class="'address' + index"
                                @click="copy(`.address${index}`)"
                                :data-clipboard-text="item.TradeTxhash"
                            >
                                {{ formatAddress(item.TradeTxhash) }}
                                <svg
                                    xmlns="http://www.w3.org/2000/svg"
                                    width="20"
                                    height="20"
                                    viewBox="0 0 20 20"
                                    fill="none"
                                >
                                    <path
                                        d="M13.2041 3.01074C14.2128 3.113 15 3.96435 15 5L15.2041 5.01074C16.2128 5.113 17 5.96435 17 7V16L16.9893 16.2041C16.8938 17.1457 16.1457 17.8938 15.2041 17.9893L15 18H8L7.7959 17.9893C6.85435 17.8938 6.1062 17.1457 6.01074 16.2041L6 16L5.7959 15.9893C4.85435 15.8938 4.1062 15.1457 4.01074 14.2041L4 14V5C4 3.96435 4.78722 3.113 5.7959 3.01074L6 3H13L13.2041 3.01074ZM6 4C5.44772 4 5 4.44772 5 5V14C5 14.5523 5.44772 15 6 15H13C13.5523 15 14 14.5523 14 14V5C14 4.44772 13.5523 4 13 4H6ZM12 13H7V12H12V13ZM12 10H7V9H12V10ZM12 7H7V6H12V7ZM7 16C7 16.5523 7.44772 17 8 17H15C15.5523 17 16 16.5523 16 16V7C16 6.44772 15.5523 6 15 6V14L14.9893 14.2041C14.8938 15.1457 14.1457 15.8938 13.2041 15.9893L13 16H7Z"
                                        fill="#3B82F6"
                                    />
                                </svg>
                            </div>
                            <div>
                                <span
                                    class="status"
                                    :class="'status' + item.Status"
                                >
                                    {{
                                        $t(
                                            `layout.${
                                                ["Processing", "", "Completed"][
                                                    item.Status
                                                ] || "Unsuccessful"
                                            }`
                                        )
                                    }}
                                </span>
                            </div>
                        </li>
                        <list-finished v-if="!loading && list.length == 0" />
                    </ul>
                </div>
                <div class="pagination">
                    <van-pagination
                        v-model="setat.pageNum"
                        :total-items="setat.total"
                        :show-page-size="3"
                        :items-per-page="setat.pageSize"
                        force-ellipses
                        @change="onRefresh"
                    >
                        <template #prev-text>
                            <van-icon name="arrow-left" />
                        </template>
                        <template #next-text>
                            <van-icon name="arrow" />
                        </template>
                    </van-pagination>
                </div>
            </div>
        </div>
    </div>
</template>

<style lang="less" scoped>
.page {
    padding: 180px 15px 15px 15px;
    .rowAward {
        display: flex;
        align-items: center;
        gap: 20px;
        .cell {
            flex: 1;
            padding: 24px;
            border-radius: 20px;
            border: 1px solid #ffccd5;
            background: #fff7f7;
            &:last-child {
                margin-bottom: 0;
            }
            .label {
                display: flex;
                align-items: center;
                font-size: 16px;
                img {
                    margin-right: 4px;
                    width: 24px;
                    height: 24px;
                }
            }
            .value {
                margin-top: 8px;
                color: #000;
                font-size: 32px;
                font-weight: 700;
                line-height: 44px; /* 137.5% */
            }
            .van-button {
                width: auto;
                height: 40px;
            }
        }
    }
    .van-form {
        margin-top: 40px;
        padding: 24px;
        border-radius: 20px;
        border: 1px solid #d9d9d9;
        .van-tabs {
            &:deep(.van-tabs__wrap) {
                height: 60px;
                background: rgba(255, 255, 255, 0.08);
                border-radius: 8px;
                overflow: hidden;
                .van-tabs__nav {
                    background: transparent;
                    gap: 20px;
                }
                .van-tab {
                    color: #000;
                    font-size: 20px;
                    border-radius: 10px;
                    border: 1px solid #d9d9d9;
                    &.van-tab--active {
                        color: #eb0029;
                        border: 1px solid #eb0029;
                    }
                }
                .van-tabs__line {
                    display: none;
                }
            }
        }
        .inputBlock {
            margin-top: 13px;
            .name {
                display: flex;
                align-items: center;
                padding-top: 40px;
                margin-bottom: 20px;
                color: #000;
                font-size: 20px;
                font-weight: 700;
                span {
                    margin-left: 8px;
                    color: #eb0029;
                    font-size: 14px;
                    font-weight: 400;
                }
            }
            .balance {
                margin-top: 8px;
                color: #949494;
                font-size: 14px;
            }
            .van-field {
                padding: 0;

                background: transparent;

                &::after {
                    display: none;
                }
                &:deep(input) {
                    font-size: 16px;
                    height: 60px;
                    padding: 0 20px;
                    color: #000;
                    border-radius: 10px;
                    border: 1px solid #d9d9d9;

                    &::-webkit-input-placeholder {
                        color: #949494;
                    }
                    &:-moz-placeholder {
                        color: #949494;
                    }
                    &::-moz-placeholder {
                        color: #949494;
                    }
                    &:-ms-input-placeholder {
                        color: #949494;
                    }
                    &:focus {
                        border: 1px solid #eb0029;
                        background: #fff7f7;
                    }
                }
            }
            .getAmount {
                display: flex;
                align-items: center;
                font-size: 16px;
                height: 60px;
                padding: 0 20px;
                color: #000;
                border-radius: 10px;
                border: 1px solid #d9d9d9;
                span {
                    color: #949494;
                }
            }
        }
        .van-button {
            margin-top: 40px;
            border-radius: 10px;
        }
    }
    .listTitle {
        margin-top: 72px;
        color: #000;
        font-size: 20px;
        font-weight: 700;
    }
    .list {
        margin-top: 22px;
        border-radius: 20px;
        border: 1px solid #d9d9d9;
        overflow: hidden;
        background: #fff;
        .head {
            display: flex;
            text-align: center;
            span {
                padding: 25px 0;
                flex: 1;
                color: #000;
                font-size: 16px;
                font-weight: 700;
                background: #f8f8f8;
            }
        }
        ul {
            li {
                display: flex;
                text-align: center;
                div {
                    padding: 22px 0;
                    border-bottom: 1px solid #d9d9d9;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    flex: 1;
                    color: #000;
                    font-size: 16px;
                    font-weight: 400;
                    svg {
                        margin-left: 8px;
                        width: 20px;
                        height: 20px;
                        cursor: pointer;
                    }
                    &.address {
                        color: #3b82f6;
                    }
                    span {
                        margin-right: 7px;
                        font-weight: 700;
                    }
                    .status {
                        display: inline-block;
                        padding: 4px 16px;
                        line-height: 18px;
                        border-radius: 30px;
                        min-width: 96px;
                        box-sizing: border-box;
                        color: #eb0029;
                        background: #ffdde3;
                        font-weight: 400;
                        &.status2 {
                            color: rgba(54, 183, 145, 1);
                            background: rgba(29, 204, 152, 0.2);
                        }
                        &.status0 {
                            color: rgba(235, 149, 0, 1);
                            background: rgba(235, 149, 0, 0.2);
                        }
                    }
                }
            }
        }
        .pagination {
            padding-top: 50px;
            text-align: right;
            padding-right: 10px;
            .van-pagination {
                display: inline-block;
            }
        }
    }
    @media (max-width: 1000px) {
        & {
            padding: 98px 15px 15px 15px;
            .rowAward {
                flex-wrap: wrap;
                gap: 0;
                .cell {
                    flex: 100% 0 0;
                    width: 100%;
                    box-sizing: border-box;
                    margin-bottom: 16px;
                    .label {
                    }
                    .value {
                        margin-top: 7px;
                        font-size: 24px;
                        line-height: 1;
                    }
                    .van-button {
                        width: auto;
                        height: 40px;
                    }
                }
            }
            .van-form {
                margin-top: 24px;
                padding: 24px;
                border-radius: 20px;
                border: 1px solid #d9d9d9;
                .van-tabs {
                    &:deep(.van-tabs__wrap) {
                        height: 48px;
                        .van-tabs__nav {
                            gap: 10px;
                        }
                        .van-tab {
                            font-size: 16px;
                            .van-tab__text--ellipsis {
                                display: inline;
                            }
                        }
                    }
                }
                .inputBlock {
                    margin-top: 11px;
                    .name {
                        padding-top: 24px;
                        margin-bottom: 12px;
                        font-size: 16px;
                        span {
                            font-size: 12px;
                        }
                    }
                    .balance {
                        font-size: 12px;
                    }
                }

                .van-button {
                    margin-top: 32px;
                }
            }
            .listTitle {
                margin-top: 60px;
            }
            .scroll {
                overflow-x: auto;
                white-space: nowrap;
                text-align: center;
            }
            .list {
                .head {
                    span {
                        padding: 20px 0;
                        flex: 100px 0 0;
                        width: 100px;
                        font-size: 14px;
                        font-weight: 700;
                        &:first-child {
                            flex: 130px 0 0;
                            width: 130px;
                        }
                    }
                }
                ul {
                    li {
                        div {
                            padding: 15px 0;
                            flex: 100px 0 0;
                            width: 100px;
                            font-size: 12px;
                            white-space: nowrap;
                            &:first-child {
                                flex: 130px 0 0;
                                width: 130px;
                            }
                            svg {
                                width: 12px;
                                height: 12px;
                                margin-left: 4px;
                            }
                            span {
                                margin-right: 3px;
                            }
                            .status {
                                min-width: auto;
                            }
                        }
                    }
                }
                .pagination {
                }
            }
        }
    }
}
</style>
